#include <stdio.h>
#include <unistd.h>
#include "iot_gpio.h"
#include "hi_io.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_uart.h"
#include "hi_uart.h"
#include "iot_errno.h"
#include "iot_gpio_ex.h"
#include "iot_i2c.h"
#include "hi_i2c.h"

#define K210_READ ((0x24 << 1) | 0x01)  //--SDA-读
#define K210_WRITE ((0x24 << 1) | 0x00) //--SDA-写

void SetAngle(unsigned int duty)
{
    unsigned int time = 20000;
    IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_3, IOT_GPIO_VALUE1);
    hi_udelay(duty);
    IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_3, IOT_GPIO_VALUE0);
    hi_udelay(time - duty);
}
void RegressMiddle(void)
{
    unsigned int angle = 1500;
    for (int i = 0; i < 10; i++)
    {
        SetAngle(angle);
    }
}
void EngineTurnLeft(void)
{
    unsigned int angle = 2500;
    for (int i = 0; i < 10; i++)
    {
        SetAngle(angle);
    }
}

void EngineTurnRight(void)
{
    unsigned int angle = 500;
    for (int i = 0; i < 10; i++)
    {
        SetAngle(angle);
    }
}

void Uart1Config(void)
{
    uint32_t ret;

    IoTGpioInit(IOT_IO_NAME_GPIO_0);

    // 设置GPIO0的管脚复用关系为UART1_TX Set the pin reuse relationship of GPIO0 to UART1_ TX
    hi_io_set_func(IOT_IO_NAME_GPIO_0, IOT_IO_FUNC_GPIO_0_UART1_TXD);
    IoTGpioInit(IOT_IO_NAME_GPIO_1);

    // 设置GPIO1的管脚复用关系为UART1_RX Set the pin reuse relationship of GPIO1 to UART1_ RX
    hi_io_set_func(IOT_IO_NAME_GPIO_1, IOT_IO_FUNC_GPIO_1_UART1_RXD);

    /* 初始化UART配置，波特率 9600，数据bit为8,停止位1，奇偶校验为NONE */
    /* Initialize UART configuration, baud rate is 9600, data bit is 8, stop bit is 1, parity is NONE */
    IotUartAttribute uart_attr = {
        .baudRate = 115200,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
    };

    ret = IoTUartInit(HI_UART_IDX_1, &uart_attr);

    if (ret != IOT_SUCCESS)
    {
        printf("Init Uart1 Falied Error No : %d\n", ret);
        return;
    }
    else
    {
        printf("Uart1 init success\n");
    }
}

void Init(void)
{
    IoTGpioInit(HI_IO_NAME_GPIO_9);

    IoTGpioSetDir(IOT_IO_NAME_GPIO_9, IOT_GPIO_DIR_OUT);
    hi_io_set_func(IOT_IO_NAME_GPIO_9, IOT_IO_FUNC_GPIO_9_GPIO);

    // IoTGpioInit(IOT_IO_NAME_GPIO_3);
    // IoTGpioSetDir(IOT_IO_NAME_GPIO_3, IOT_GPIO_DIR_OUT);
    // hi_io_set_func(IOT_IO_NAME_GPIO_3, IOT_IO_FUNC_GPIO_3_GPIO);

    // 先初始化引脚
    IoTGpioInit(HI_IO_NAME_GPIO_13);
    IoTGpioInit(HI_IO_NAME_GPIO_14);

    // 将引脚功能设置为I2C引脚
    hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_I2C0_SDA);
    hi_io_set_func(HI_IO_NAME_GPIO_14, HI_IO_FUNC_GPIO_14_I2C0_SCL);

    // 初始化iic0
    if (hi_i2c_init(HI_I2C_IDX_0, 100000) != 0)
    {
        printf("I2c init err!\n");
    }
    hi_i2c_set_baudrate(HI_I2C_IDX_0, 100000);
    printf("I2C Test Start\n");
    Uart1Config();
}

// 读取数据
static uint32_t K210_Read(uint8_t *data, uint32_t dataLen)
{
    hi_i2c_idx id = 0;
    hi_i2c_data i2cData;
    i2cData.receive_buf = data;
    i2cData.receive_len = dataLen;
    i2cData.send_buf = NULL;
    i2cData.send_len = 0;
    uint32_t result;
    result = hi_i2c_read((hi_i2c_idx)id, K210_READ, &i2cData);
    if (result != IOT_SUCCESS)
    {
        printf("K210_Read() Failed ,%0X\n", result);
        return result;
    }
    return IOT_SUCCESS;
}
static void *i2c_demo_task(void)
{
    hi_u32 ret;
    uint8_t *data = "1";
    while (1)
    {
        osDelay(50);
        ret = K210_Read(data, 1);
        if (ret == 0)
            // printf(*data);

        usleep(2500000);
    }
    return 0;
}
static void UartReceiveMessage_1(void)
{
    static char *recBuffer[10];
    int g_ReceivedDatalen = IoTUartRead(HI_UART_IDX_1, recBuffer, 1);
    if (g_ReceivedDatalen > 0)
    {
        printf("asrpro rcvData len:%d,msg:%s.\n", g_ReceivedDatalen, recBuffer);
        if (recBuffer[0] == '1')
        {
            EngineTurnLeft();
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_9, 1);
        }
        else if (recBuffer[0] == '3')
        {
            // EngineTurnRight();
            IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_9, 0);
        }
        else if (recBuffer[0] == '4')
        {
            RegressMiddle();
        }
        memset(recBuffer, 0, sizeof(recBuffer));
        g_ReceivedDatalen = 0;
    }
}

static void *asrpro(void)
{
    while (1)
    {
        osDelay(50);
        UartReceiveMessage_1(); // Collecting Serial Port Data
        usleep(2500000);
    }
    return 0;
}

static void IotMainEntry(void)
{
    Init();
    osThreadAttr_t attr;

    // Create the IoT Main task
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = 25;
    attr.name = "IoTMain";
    (void)osThreadNew((osThreadFunc_t)i2c_demo_task, NULL, (const osThreadAttr_t *)&attr);

    osThreadAttr_t attr2;

    attr2.name = "asrpro";
    attr2.attr_bits = 0U;
    attr2.cb_mem = NULL;
    attr2.cb_size = 0U;
    attr2.stack_mem = NULL;
    attr2.stack_size = 1024 * 2;
    attr2.priority = 20;

    if (osThreadNew((osThreadFunc_t)asrpro, NULL, &attr2) == NULL)
    {
        printf("Falied to create asrpro!\n");
    }
}
APP_FEATURE_INIT(IotMainEntry);